<template>
	<div>
		<Modal
			:title="L('ChangeTenant')"
			:value="value"
			@on-ok="changeTenant"
			@on-visible-change="visibleChange"
			draggable
		>
			<Input :placeholder="L('TenancyName')" v-model="changedTenancyName" />
			<div v-if="!changedTenancyName" style="margin-top:10px">{{L('LeaveEmptyToSwitchToHost')}}</div>
			<div slot="footer">
				<Button @click="cancel">{{L('Cancel')}}</Button>
				<Button @click="changeTenant" type="primary">{{L('OK')}}</Button>
			</div>
		</Modal>
	</div>
</template>
<script lang="ts">
	import { Component, Prop } from "vue-property-decorator";
	import Utils from "../core/utils/Utils";
	import AppBase from "../core/utils/AppBase";
	@Component
	export default class TenantSwitch extends AppBase {
		@Prop({ default: false }) value!: boolean;
		changedTenancyName = "";
		get tenant() {
			return this.$store.state.session.tenant;
		}
		cancel() {
			this.$emit("input", false);
		}
		visibleChange(value: boolean) {
			if (!value) {
				this.$emit("input", value);
			} else {
				this.changedTenancyName = this.$store.state.session.tenant
					? this.$store.state.session.tenant.name
					: "";
			}
		}
		async changeTenant() {
			if (!this.changedTenancyName) {
				Utils.setTenantIdCookie("");
				location.reload();
				return;
			} else {
				const tenant = await this.$store.dispatch({
					type: "account/isTenantAvailable",
					data: { tenancyName: this.changedTenancyName }
				});
				switch (tenant.state) {
					case 1:
						Utils.setTenantIdCookie(tenant.tenantId);
						location.reload();
						return;
					case 2:
						break;
					case 3:
						break;
				}
			}
		}
	}
</script>

